﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SSE657.BahMap.Common;
using System.IO;

namespace SSE657.BahMap.DataAccess.Text
{
    public class SchoolDataTextConnector : TextDataConnectorBase, ISchoolDataConnector
    {
        public IEnumerable<SchoolData> GetSchools(int zipcode)
        {
            List<SchoolData> schools = new List<SchoolData>();
            string filename = "schools.txt";
            StreamReader file = new StreamReader(Path.Combine(_rootDirectory, filename));
            string line = file.ReadLine();
            while (line != null)
            {
                SchoolData school = GetSchoolData(line);
                if (school.ZipCode == zipcode)
                    schools.Add(GetSchoolData(line));
                line = file.ReadLine();
            }
            return schools;
        }

        public IEnumerable<SchoolData> GetSchools(string mha)
        {
            List<SchoolData> schools = new List<SchoolData>();
            string filename = "schools.txt";
            HashSet<int> zips = new HashSet<int>(_mhaAreas[mha].ZIPs);
            StreamReader file = new StreamReader(Path.Combine(_rootDirectory, filename));
            string line = file.ReadLine();
            while (line != null)
            {
                SchoolData school = GetSchoolData(line);
                if (zips.Contains(school.ZipCode))
                    schools.Add(GetSchoolData(line));
                line = file.ReadLine();
            }
            return schools;
        }

        private SchoolData GetSchoolData(string fileLine)
        {
            //SchoolName|ZIP|InStateTuition|OutOfStateTuition|InStateFees|OutOfStateFees|Type
            string[] words = fileLine.Split('|');
            return new SchoolData()
            {
                SchoolName = words[0],
                ZipCode = Int32.Parse(words[1]),
                InStateTuition = Double.Parse(words[2]),
                OutOfStateTuition = Double.Parse(words[3]),
                InStateFees = Double.Parse(words[4]),
                OutOfStateFees = Double.Parse(words[5]),
                SchoolType = (SchoolType)Enum.Parse(typeof(SchoolType), words[6])
            };
        }
    }
}
